import { Typography, Image, Spin } from 'antd';
import { useEffect, useRef, useState } from 'react';
import '../../assets/css/blogs.css';
import { generateBlogImage } from './utils';

const { Title } = Typography;

import blogData from './mock';

interface BlogItem {
  id: number;
  image: string;
  title: string;
  theme: string;
  abstract: string;
  url: string;
}

const Blogs = () => {
  const [blogs, setBlogs] = useState<BlogItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedCategory, setSelectedCategory] = useState('全部');
  const [hasMore, setHasMore] = useState(true);
  const blogsGridRef = useRef<HTMLDivElement>(null);
  const abortControllerRef = useRef<AbortController | null>(null);

  // 从mock数据中获取博客数据
  const mockBlogs = (page: number): BlogItem[] => {
    const filteredData = selectedCategory === '全部' 
      ? blogData 
      : blogData.filter(item => item.theme === selectedCategory);
    const pageSize = 6;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const pageData = filteredData.slice(start, end);
    return pageData.map((blog, index) => ({
      id: Date.now() + index,
      image: generateBlogImage(blog),
      title: blog.title,
      theme: blog.theme,
      abstract: blog.title,
      url: blog.url
    }));
  };

  // 加载更多博客
  const loadMoreBlogs = async () => {
     if (!hasMore) return; 

    // 取消之前的请求
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }

    // 创建新的 AbortController
    const abortController = new AbortController();
    abortControllerRef.current = abortController;
    
    let isCancelled = false;
    const currentCategory = selectedCategory;
    setLoading(true);

    try {
      // 使用 signal 来控制请求的取消
      await new Promise((resolve, reject) => {
        const timeoutId = setTimeout(resolve, 1000);
        const handleAbort = () => {
          clearTimeout(timeoutId);
          isCancelled = true;
          reject(new Error('Request aborted'));
        };
        abortController.signal.addEventListener('abort', handleAbort);
      });

      // 检查分类是否已改变或请求已被取消
      if (currentCategory !== selectedCategory || isCancelled || abortController.signal.aborted) {
        setLoading(false);
        return;
      }

      const newBlogs = mockBlogs(currentPage);

      // 再次检查分类是否已改变或请求已被取消
      if (currentCategory !== selectedCategory || isCancelled || abortController.signal.aborted) {
        setLoading(false);
        return;
      }

      if (newBlogs.length === 0) {
        setHasMore(false);
      } else {
        setBlogs(prev => [...prev, ...newBlogs]);
        setCurrentPage(prev => prev + 1);
      }
    } catch (error) {
      if (!isCancelled && error.message !== 'Request aborted') {
        console.error('加载博客失败:', error);
      }
    } finally {
      if (!isCancelled && !abortController.signal.aborted) {
        setLoading(false);
        abortControllerRef.current = null;
      }
    }
  };

  // 初始加载
  useEffect(() => {
    setBlogs([]);
    setCurrentPage(1);
    setHasMore(true);
    loadMoreBlogs();

    // 清理函数：组件卸载或依赖项改变时取消正在进行的请求
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
        abortControllerRef.current = null;
      }
    };
  }, [selectedCategory]);

  // 滚动加载更多（接近底部 1/5 时）
  useEffect(() => {
    const handleScroll = () => {
      const container = blogsGridRef.current;
      if (!container || loading || !hasMore) return;

      const { scrollTop, scrollHeight, clientHeight } = container;

      // 到达底部 1/5 范围内
      if (scrollHeight - scrollTop - clientHeight < clientHeight / 5) {
        loadMoreBlogs();
      }
    };
    const container = blogsGridRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (container) {
        container.removeEventListener('scroll', handleScroll);
      }
    };
  }, [loading, hasMore]);

  const categories = ['全部', '前端','React', 'Vue', 'WebGL', 'GIS','工程化',  '性能优化', '原理', '前沿'];
  const [scrollPosition, setScrollPosition] = useState(0);

  // 窗口大小变化时更新滚动位置
  useEffect(() => {
    const handleResize = () => {
      const container = categoryFilterRef.current;
      if (container) {
        setScrollPosition(container.scrollLeft);
      }
    };

    window.addEventListener('resize', handleResize);
    handleResize(); // 初始调用
    return () => window.removeEventListener('resize', handleResize);
  }, [scrollPosition, window.innerWidth]); // 添加window.innerWidth依赖
  const categoryFilterRef = useRef<HTMLDivElement>(null);

  const handleScroll = (direction: 'left' | 'right') => {
    const container = categoryFilterRef.current;
    if (!container) return;

    const scrollAmount = 200; // 每次滚动的距离
    const newPosition = direction === 'left' 
      ? Math.max(0, scrollPosition - scrollAmount)
      : Math.min(container.scrollWidth - container.clientWidth, scrollPosition + scrollAmount);
    
    container.scrollTo({
      left: newPosition,
      behavior: 'smooth'
    });
    setScrollPosition(newPosition);
  };

  return (
    <section id="blogs" className="blogs-section bg-white relative z-1">
      <div className="blogs-container">
        <Title level={1} className="section-title">博客</Title>
        {/* 分类筛选 */}
        <div className="category-filter-container" style={{ position: 'relative', width: '100%' }}>
          <button 
            className="scroll-button left" 
            onClick={() => handleScroll('left')}
            style={{
              display: scrollPosition > 0 ? 'block' : 'none',
              position: 'absolute',
              left: 0,
              top: '50%',
              transform: 'translateY(-50%)',
              zIndex: 1,
              background: '#fff',
              border: '1px solid #ddd',
              borderRadius: '50%',
              width: '32px',
              height: '32px',
              cursor: 'pointer',
              boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}
          >
            ←
          </button>
          <div 
            ref={categoryFilterRef}
            className="category-filter" 
            style={{ 
              display: 'flex', 
              gap: '8px', 
              overflowX: 'auto',
              scrollBehavior: 'smooth',
              padding: '0 40px',
              msOverflowStyle: 'none',
              scrollbarWidth: 'none',
              '@media (maxWidth: 768px)': {
                padding: '0 32px',
                gap: '6px'
              }
            }}
            onScroll={(e) => setScrollPosition(e.currentTarget.scrollLeft)}
          >
            {categories.map(category => (
              <button
                key={category}
                className={`category-button ${selectedCategory === category ? 'active' : ''}`}
                onClick={() => {
                  setSelectedCategory(category);
                  setCurrentPage(1);
                  setBlogs([]);
                  if (blogsGridRef.current) {
                    blogsGridRef.current.scrollTop = 0;
                  }
                }}
                style={{ 
                  flexShrink: 0,
                  padding: '8px 16px',
                  borderRadius: '20px',
                  border: '1px solid #e8e8e8',
                  background: selectedCategory === category ? '#1890ff' : '#fff',
                  color: selectedCategory === category ? '#fff' : '#333',
                  transition: 'all 0.3s ease',
                  fontSize: window.innerWidth <= 768 ? '14px' : '16px',
                  whiteSpace: 'nowrap'
                }}
              >
                {category}
              </button>
            ))}
          </div>
          <button 
            className="scroll-button right" 
            onClick={() => handleScroll('right')}
            style={{
              display: categoryFilterRef.current && scrollPosition < (categoryFilterRef.current.scrollWidth - categoryFilterRef.current.clientWidth) ? 'block' : 'none',
              position: 'absolute',
              right: 0,
              top: '50%',
              transform: 'translateY(-50%)',
              zIndex: 1,
              background: '#fff',
              border: '1px solid #ddd',
              borderRadius: '50%',
              width: '32px',
              height: '32px',
              cursor: 'pointer',
              boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}
          >
            →
          </button>
        </div>

        {/* 博客列表（限制高度并滚动） */}
        <div className="blogs-grid" ref={blogsGridRef}>
          {blogs.map((blog) => (
            <div key={blog.id} className="blog-item" onClick={() => window.open(blog.url, '_blank')} style={{ cursor: 'pointer' }}>
              <Image
                src={blog.image}
                alt={blog.title}
                className="blog-image"
                preview={false}
              />
              <div className="blog-info">
                <h3 className="blog-title">{blog.title}</h3>
                <div className="blog-meta">
                  <span>{blog.abstract}</span>
                </div>
              </div>
            </div>
          ))}
          {loading && (
            <div className="loading-container">
              <Spin size="large" />
            </div>
          )}
        </div>
      </div>
    </section>
  );
};

export default Blogs;
